<template>
  <div class="home">
    <van-divider dashed :style="{ color: '#1989fa', borderColor: '#1989fa',margin:'0px',fontSize: '24px' }">
      运行状态
    </van-divider>
    <van-row>
      <van-col span="8"><strong>电压:{{ status.voltage.toFixed(2) }}V</strong></van-col>
      <van-col span="8"><strong>电流:{{ status.current.toFixed(2) }}A</strong></van-col>
      <van-col span="8"><strong>功率:{{ (status.voltage * status.current).toFixed(2) }}W</strong></van-col>
    </van-row>
    <van-row style="margin-top: 10px;">
      <van-col span="8"><strong>设定:{{ status.targetTemp }}℃</strong></van-col>
      <van-col span="16"><strong>当前:{{ status.currTemp }}℃</strong></van-col>
    </van-row>
    <div style="position:relative;margin-top:-24px;top:40px;float: right; ">
      <span>固定y轴：</span>
      <van-switch size="16" v-model="fixedAxes" @change="fixedAxesChange"/>
    </div>
    <canvas id="myChart" style="margin-top: 16px"></canvas>
    <van-divider dashed :style="{ color: '#1989fa', borderColor: '#1989fa',margin:'0px',fontSize: '24px' }">
      温度设定
    </van-divider>

    <div style="margin-top: 8px;">
      <div>
        <span>{{ status.minTemp }}</span>
        <span style="float: right">{{ status.maxTemp }}</span>
      </div>
      <van-slider v-model="status.targetTemp" :max="status.maxTemp" :min="status.minTemp" :step="1"
                  @change="slidChange" bar-height="10px" active-color="#ee0a24">
        <template #button>
          <div class="slider-button">{{ status.targetTemp }}℃</div>
        </template>
      </van-slider>
    </div>
    <div style="margin-top: 16px;">
      <van-stepper v-model="status.stepVal" :min="status.minTemp" :max="status.maxTemp" @change="stepChange"
                   integer/>
    </div>
    <div style="height: 40px;padding-bottom: 30px;margin-top: 16px;">
      <van-button round :type="hotButton.state ? 'danger' : 'info'" @click="hotHandler" size="large" :block="true">
        {{ hotButton.state ? hotButton.startStr : hotButton.stopStr }}
      </van-button>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import {Button, Slider, Divider, Stepper, Toast, Row, Col, Switch} from 'vant';
import Chart from 'chart.js/auto';
import websocket from "@/util/websocket";
import {getAction} from "@/util/request";

Vue.use(Button).use(Slider).use(Divider).use(Stepper).use(Toast).use(Row).use(Col).use(Switch)

export default {
  name: 'HomeView',
  data() {
    return {
      hotButton: {
        startStr: "停止加热",
        stopStr: "开始加热",
        state: false,
      },
      url:{
        state:"/state"
      },
      historicalTemp: [],
      status: {
        voltage: 0,
        current: 0,
        //温度上限
        maxTemp: 280,
        //温度下限
        minTemp: 0,
        //当前温度
        currTemp: 25,
        //目标温度
        targetTemp: 0,
        stepVal: 0
      },
      lineChart: null,
      fixedAxes: true,
      refreshTimer: null,
      loading:false
    }
  },
  watch: {
    // 此处监听obj属性a值变量
    'status.targetTemp'(newVal, oldVal) {
      this.status.stepVal = newVal
    },
    deep: true
  },
  mounted: function () {
    let lineChart = document.getElementById('myChart');
    const config = {
      type: 'line',
      options: {
        animations: false,
        scales: this.getScale(),
        plugins: {
          legend: {
            align: 'start'
          }
        }
      },
      data: {
        labels: [],
        datasets: [
          {
            label: '设定温度',
            data: [],
          }, {
            label: '当前温度',
            data: [],
            tension: 0.4,
          }
        ]
      }
    };

    this.lineChart = new Chart(lineChart, config);
    if (process.env.NODE_ENV === 'production') {
      websocket.registerHandler(this.name, "state", this.stateHandler)
    } else {
      this.refreshTimer = setInterval(() => {
        getAction("/state")
            .then(res => {
                  if (this.historicalTemp.length > 200)
                    this.historicalTemp.shift()
                  this.hotButton.state = res.heating
                  this.status.voltage = res.voltage
                  this.status.current = res.current
                  this.status.currTemp = res.currTemp.toFixed(2)
                  this.historicalTemp.push(res.currTemp)
                  this.status.targetTemp = res.targetTemp

                  this.dataRefresh()
                }
            )
      }, 500)
    }
  },
  destroyed: function () {
    if (this.refreshTimer) {
      clearInterval((this.refreshTimer))
    }
    websocket.unregisterHandler(this.name)
  },
  methods: {
    hotHandler() {
      this.loading=true
      let set = {
        heating:  !this.hotButton.state
      }

      getAction(this.url.state,set)
      .then(res=>{
        this.hotButton.state = res.heating
      })
      .finally(res=>this.loading=false)
    },
    dataRefresh() {
      let labels = [];
      let setTemp = [];
      for (let i = 0; i < this.historicalTemp.length; ++i) {
        labels.push(i.toString());
        setTemp.push(this.status.targetTemp)
      }
      this.lineChart.data.labels = labels
      this.lineChart.data.datasets[0].data = setTemp;
      this.lineChart.data.datasets[1].data = this.historicalTemp
      this.lineChart.update();
    },
    slidChange() {
      this.loading=false
      let set = {
        temp: this.status.targetTemp
      }

      getAction(this.url.state,set)
      .then(res=>{

      })
      .finally(res=>this.loading=true)
    },
    stepChange(value) {
      if (value != this.status.targetTemp) {
        this.status.targetTemp = value
        this.slidChange()
      }
    },
    stateHandler(json) {
      if (this.historicalTemp.length > 100)
        this.historicalTemp.shift()
      this.hotButton.state = json.state
      this.status.voltage = json.U
      this.status.current = json.I
      this.status.currTemp = json.T.toFixed(2)
      this.historicalTemp.push(json.T)
      this.status.targetTemp = json.targetTemp
      this.dataRefresh()
    },
    getScale() {
      if (!this.fixedAxes)
        return {}
      else
        return {
          y: {
            suggestedMin: 0,
            suggestedMax: this.status.maxTemp + 20
          }
        }
    },
    fixedAxesChange(value) {
      this.lineChart.options.scales = this.getScale()
    }
  }
}
</script>
<style scoped>
.home {
  padding: 5px;
  margin: 0 auto;
}

.slider-button {
  width: 26px;
  color: #fff;
  font-size: 10px;
  line-height: 18px;
  text-align: center;
  background-color: #ee0a24;
  border-radius: 100px;
}
</style>
